/* 聊天窗口
 * 其中54px为回复框高度，css同
 * mode true为文本，false为语音
 * cancel true为取消录音，false为正常录音完毕并发送
 * 上拉超过50px为取消发送语音
 * status 0为normal，1为pressed，2为cancel
 * hud的尺寸是150*150
 */
//同声传译文档地址
//https://mp.weixin.qq.com/wxopen/pluginbasicprofile?action=intro&appid=wx069ba97219f66d99&token=1756564058&lang=zh_CN
const preset = require('./preset.js')
const util = require('../../../utils/util.js')
const WxUtil = require('../../../utils/WxUtil.js')
//智能聊天api地址
const chatApi = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat";
const app = getApp();

//下面两个为同声传译插件
const plugin = requirePlugin("WechatSI")
const manager = plugin.getRecordRecognitionManager()
Page({
  data: {
    userInfo: { "avatarUrl": '/image/icon/user-unlogin.png'},
    logged: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    langType: "zh_CN",
    contentInput:'',
    message_list: [{
        myself: 0,
        head_img_url: '/image/tool/ai_android.jpg',
        msg_type: 'text',
        content: '我是聊天智能机器人，快来和我聊天吧。'
      }
    ],
    scroll_height: wx.getSystemInfoSync().windowHeight,
    mode: true, //标识语音与文本模式
    cancel: false,
    status: 0,
    tips: ['按住 说话', '松开 结束', '取消 发送'],
    state: {
      'normal': 0,
      'pressed': 1,
      'cancel': 2
    },
    toView: ''
  },

  /**
   * 修改翻译类型 中文|英文
   */
  changeLang: function (event) {
    let dataset = event.target.dataset;
    let type = dataset.type;

    this.setData({
      langType: type
    });
  },

  //清空缓存
  clearCache: function () {
    wx.removeStorageSync("chatCacheList");
    this.setData({
      message_list: this.data.message_list.slice(0, 1)
    });
  },

  //发送问题
  reply: function () {
    var content = this.data.contentInput;
    if (content == '') {
      wx.showToast({
        image:'/image/icon/icon_error.png',
        title: '请说点什么吧'
      });
      return;
    }

    //去问机器人
    this.chat_ask(content);
  },

  /**
   * 机器人回答内容
   */
  robotAnswer: function (content)
  {
    let that = this;
    var message_list = this.data.message_list;
    var message = {
      myself: 0,
      head_img_url: '/image/tool/ai_android.jpg',
      msg_type: 'text',
      content: content,
      create_time: util.formatTime(new Date())
    }

    console.info("====回答===" + content);
    
    //如果是中文
    if (this.data.langType =="zh_CN")
    {
      message_list.push(message);
      this.setData({
        message_list: message_list
      });

      //缓存聊天记录
      try {
        wx.setStorageSync("chatCacheList", message_list.slice(1, message_list.length));
      } catch (e) {

      }
      this.scrollToBottom();

      //文字转成语音
      plugin.textToSpeech({
        lang: "zh_CN",
        tts: true,
        content: content,
        success: function (res) {
          that.playVoice(res.filename);
        },
        fail: function (res) {
          console.log("fail tts", res)
        }
      })
    }

    //如果是英文
    if (this.data.langType == "en_US") {
      //翻译并播放翻译后的声音
      plugin.translate({
        lfrom: 'zh_CN',
        lto: 'en_US',
        content: content,
        tts: true,
        success: (resTrans) => {

          let passRetcode = [
            0, // 翻译合成成功
            -10006, // 翻译成功，合成失败
            -10007, // 翻译成功，传入了不支持的语音合成语言
            -10008, // 翻译成功，语音合成达到频率限制
          ]

          if (passRetcode.indexOf(resTrans.retcode) >= 0) {
            
            message.content = resTrans.result;
            message_list.push(message);
            that.setData({
              message_list: message_list
            });

            //缓存聊天记录
            try {
              wx.setStorageSync("chatCacheList", message_list.slice(1, message_list.length));
            } catch (e) {

            }

            that.scrollToBottom();
            that.playVoice(resTrans.filename);

          }
        },
        fail: function (resTrans) {
          console.error("调用失败", resTrans)
        },
        complete: resTrans => {
          
        }
      })
    }
    
  },
  //聊天，向机器人发问
  chat_ask:function(question) {

    console.info("===chat_ask====" + this.data.langType);
    console.info(question);
    //========在屏幕显示问题开始=========
    var message_list = this.data.message_list;
    var message = {
      myself: 1,
      head_img_url: '/image/icon/user-unlogin.png',
      msg_type: 'text',
      content: question,
      create_time: util.formatTime(new Date())
    }
    message_list.push(message);
    this.setData({
      message_list: message_list,
      contentInput: '' // 清空输入框文本
    })

    //缓存聊天记录
    try{
      wx.setStorageSync("chatCacheList", message_list.slice(1, message_list.length));
    }catch(e)
    {

    }
   

    this.scrollToBottom();
    //========在屏幕显示问题结束=========
    //========以下为调用聊天接口==========
    let that = this;
    let time = new Date().getTime();
    let app_id = app.globalData.aiAppId;
    let time_stamp = parseInt(new Date().getTime() / 1000);
    let nonce_str = WxUtil.getRandStr();
    let session = app.globalData.openid.substring(0, 6) + time;
    //question = WxUtil.textHandle(question);

    let params = {
      nonce_str: nonce_str,
      question: question,
      time_stamp: time_stamp,
      session: session,
      app_id: app_id
    }

    //如果选择的是英文,则翻译成中文后，现调机器人接口
    if (this.data.langType=='en_US')
    {
      plugin.translate({
        lfrom: 'en_US',
        lto: 'zh_CN',
        content: question,
        tts: true,
        success: (resTrans) => {

          let passRetcode = [
            0, // 翻译合成成功
            -10006, // 翻译成功，合成失败
            -10007, // 翻译成功，传入了不支持的语音合成语言
            -10008, // 翻译成功，语音合成达到频率限制
          ]
          if (passRetcode.indexOf(resTrans.retcode) >= 0) {
            
            params.question = resTrans.result;
            let sign = WxUtil.getReqSign(params);
            params.sign = sign;

            that.callChatApi(params);
          }
        },
        fail: function (resTrans) {
          console.error("调用失败", resTrans)
        },
        complete: resTrans => {
          
        }
      })
    }

    //如果是中文
    if (this.data.langType == 'zh_CN') {
      let sign = WxUtil.getReqSign(params);
      params.sign = sign;

      this.callChatApi(params);
    }
  },

  //调用智能聊天接口(这儿肯定是中文了，聊天接口只支持中文)
  callChatApi: function (params) {

    var anw = preset.presetQuestion(params.question);
    //如果过滤到有可能是预设的问题。
    if (null != anw && "" != anw)
    {
      this.robotAnswer(anw);
      return;
    }

    let that=this;
    wx.request({
      url: chatApi,
      method: 'post',
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.info("===调用聊天接口返回====");
        console.info(res);

        //调用成功
        if (res.data.msg=="ok")
        {
          that.robotAnswer(res.data.data.answer);
        }else
        {
          that.robotAnswer(preset.getErrorMsg());
        }
      },
      fail: function (error) {
        console.error(error)
      }
    })
  },

  switchMode: function () {
    // 切换语音与文本模式
    this.setData({
      mode: !this.data.mode
    });
  },
  //开始录音
  record: function () {    
    console.info("调用开始录音===");
    manager.start({lang:this.data.langType});
  },
  //结束录音
  stop: function () {
    //wx.stopRecord();
    manager.stop()
  },
  touchStart: function (e) {
    // 触摸开始
    var startY = e.touches[0].clientY;
    // 记录初始Y值
    this.setData({
      startY: startY,
      status: this.data.state.pressed
    });
  },
  touchMove: function (e) {
    // 触摸移动
    var movedY = e.touches[0].clientY;
    var distance = this.data.startY - movedY;
    // console.log(distance);
    // 距离超过50，取消发送
    this.setData({
      status: distance > 50 ? this.data.state.cancel : this.data.state.pressed
    });
  },
  touchEnd: function (e) {
    // 触摸结束
    var endY = e.changedTouches[0].clientY;
    var distance = this.data.startY - endY;
    // console.log(distance);
    // 距离超过50，取消发送
    this.setData({
      cancel: distance > 50 ? true : false,
      status: this.data.state.normal
    });
    // 不论如何，都结束录音
    this.stop();
  },
  scrollToBottom: function () {
    this.setData({
      toView: 'row_' + (this.data.message_list.length - 1)
    });
  },
  /**
   * 
   */
  bindInputValue(event) {
    let value = event.detail.value;
    this.setData({
      contentInput: event.detail.value,
    });
  },

  //播放声音
  playVoice(filePath) {
    wx.playBackgroundAudio({
      dataUrl: filePath,
      success: (res) => {
      },
      fail: (res) => {
      },
      complete: function (res) {
        
      }
    })
  },
  /**
   * 初始化语音识别回调
   * 绑定语音播放开始事件
   */
  initRecord: function () {
    //有新的识别内容返回，则会调用此事件
    manager.onRecognize = (res) => {
      console.info("====onRecognize===");
      console.info(res);
    }

    // 语音识别结束，返回识别结果
    manager.onStop = (res) => {
      let text = res.result;

      console.info("语音识别的结果==" + text);

      //去问机器人
      this.chat_ask(text);
    }

    // 识别错误事件
    manager.onError = (res) => {
      wx.showToast({
        title: '没听清楚你说的是什么',
      })
      console.info("====onError===");
      console.info(res);
    }

    // 语音播放开始事件
    wx.onBackgroundAudioPlay(res => {

    })
  },
  onLoad: function () {
    this.initRecord();
    app.getRecordAuth();

    try {
      let chatCacheList = wx.getStorageSync("chatCacheList");

      if (chatCacheList)
      {
        this.setData({
          message_list: this.data.message_list.concat(chatCacheList)
        });
      }
      
    } catch (e) {

    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                userInfo: res.userInfo
              });
              app.globalData.userInfo = res.userInfo;
            }
          })
        }
      }
    })
  },
  onGetUserInfo: function (e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        userInfo: e.detail.userInfo
      })

      app.globalData.userInfo = e.detail.userInfo;
    }
  },
  onShareAppMessage: function () {

  }
})